var common = require('../../utils/common.js');
var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var Base = require('../base.js');
var app = getApp();

const ANI_Time = 300;

var ShareActionSheet = function({
  page,
  scope,
  cmpt
}) {
  Base.apply(this, arguments);
  this.init();
}

common.extend(ShareActionSheet, Base);

Object.assign(ShareActionSheet.prototype, {
  init() {
    var _self = this;
    var cmpt = this.curCmpt;

    this.setData({
      asShow: false,
      asAniData: null,
      asMaskAniData: null,
      gening: false,
    }, true);
  },

  show(params) {
    if (!this.asAni) {
      this.asAni = wx.createAnimation({
        duration: ANI_Time,
        timingFunction: 'ease',
      });
    }
    if (!this.asMaskAni) {
      this.asMaskAni = wx.createAnimation({
        duration: ANI_Time,
        timingFunction: 'ease',
      });
    }

    this.asAni.translateY(0).step();
    this.asMaskAni.opacity(1).step();

    this.showParams = params || {};
    this.setData({
      asShow: true
    }, true);
    setTimeout(() => {
      this.setData({
        asAniData: this.asAni.export(),
        asMaskAniData: this.asMaskAni.export(),
      }, true);
    }, 100)
  },

  hide() {
    this.asAni.translateY('100%').step();
    this.asMaskAni.opacity(0).step();

    this.setData({
      asAniData: this.asAni.export(),
      asMaskAniData: this.asMaskAni.export(),
    }, true);
    setTimeout(() => {
      this.setData({
        asShow: false
      }, true);
    }, ANI_Time)
  },

  /**
   * 生成分享图片
   * @return {[type]} [description]
   */
  genShareImg() {
    var params = this.showParams;
    var paramsStr = 'userSid=' + app.getUserSid() + '&alias=' + app.getAlias() + '&sid=' + app.globalData.sid;

    Object.keys(params).forEach(function(key) {
      var val = params[key];
      paramsStr += '&' + key + '=' + val;
    });

    // ajax.G('/openapi/CImage/getsharePic', params, (result) => {});

    var url = app.getHost() + '/openapi/CImage/getsharePic?' + paramsStr;

    this.setData({
      gening: true
    }, true);
    wx.downloadFile({
      url,
      success: (res) => {
        if (res.statusCode === 200) {
          var path = res.tempFilePath;

          this.setData({
            gening: false
          }, true);
          wx.navigateTo({
            url: '/pages/shareImg/index?url=' + path,
          });
        } else {
          this.setData({
            gening: false
          }, true);
          util.showWarn('分享图片生成失败');
        }
      },
      fail: () => {
        this.setData({
          gening: false
        }, true);
        util.showWarn('分享图片生成失败');
      }
    });
  }
});

module.exports = ShareActionSheet;